<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 注意提示区域 -->
      <el-row>
        <el-col>
          <el-alert title="注意:只能选择三级菜单选项" type="warning" show-icon>
          </el-alert>
        </el-col>
      </el-row>
      <!-- 选择商品分类参数区域 -->
      <el-row class="row_style">
        <el-col>
          <span style="margin-right:8px">选择商品分类:</span> 
          <el-cascader v-model="cateOption" :options="catelist" 
            :props="castProps" clearable @change="cateChange">
            </el-cascader>
        </el-col>
      </el-row>
      <!-- 属性参数区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数 区域 -->
        <el-tab-pane label="动态参数" name="many">
           <el-button type="primary" :disabled="isBtnDisable"  @click="addDialogVisible = true">添加参数</el-button>
           <el-table :data="manyTableDate" border stripe>
            <!-- 展开行 -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" @close="handleClose(index,scope.row)" closable>
                    {{ item }}
                  </el-tag>
                  <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput"
                    size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)" >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column prop="attr_name" label="参数名称"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <!-- 编辑按钮 -->
                  <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                  <!-- 删除按钮 -->
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteDialog(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
           </el-table>
        </el-tab-pane>
        <!-- 静态参数 区域 -->
        <el-tab-pane label="静态参数" name="only">
           <el-button type="primary" :disabled="isBtnDisable"  @click="addDialogVisible = true">添加属性</el-button>
           <el-table :data="onlyTableDate" border stripe>
              <!-- 静态参数展开行 区域 -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" @close="handleClose(index,scope.row)" closable>
                    {{ item }}
                  </el-tag>
                  <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput"
                    size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)" >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column prop="attr_name" label="参数名称"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <!-- 编辑按钮 -->
                  <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                  <!-- 删除按钮 -->
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteDialog(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
           </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 编辑参数/属性 对话框 -->
    <el-dialog :title=" '添加' + titleText" :visible.sync="editDialogVisible" width="50%">
      <el-form :model="editInfoForm" :rules="editInfoRules" ref="editInfoRef" label-width="80px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editInfoForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加 参数/属性 对话框 -->
    <el-dialog :title=" '修改' + titleText" :visible.sync="addDialogVisible" width="50%"
    @close="addInfoClose">
      <el-form :model="addInfoForm" :rules="addInfoRules" ref="addInfoRef" label-width="80px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addInfoForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data(){
    return{
      // 商品列表分类数据
      catelist:[],
      // 级联选择器配置选项
      castProps:{
        expandTrigger:'hover',
        value:"cat_id",
        label:"cat_name",
        children:"children"
      },
      // 选择的三级选项
      cateOption:[],
      // 被激活的页签
      activeName:"many",
      // 获取到的动态参数列表
      manyTableDate:[],
      // 获取到的静态参数列表
      onlyTableDate:[],
      // 控制添加 属性/参数 对话框的展示
      addDialogVisible:false,
      // 添加 属性/参数 表单
      addInfoForm:{
        attr_name:''
      },
      // 添加 属性/参数 表单验证规则
      addInfoRules:{
        attr_name:[
          { required: true, message: '请输入名称', trigger: 'blur' }
        ]
      },
      // 控制编辑 属性/参数 对话框的展示
      editDialogVisible:false,
      // 编辑 属性/参数 表单
      editInfoForm:{
        attr_id:"",
        attr_name:''
      },
      // 编辑 属性/参数 表单验证规则
      editInfoRules:{
        attr_name:[
          { required: true, message: '请输入名称', trigger: 'blur' }
        ]
      },
      
    }
  },
  created(){
    this.getCateList();
  },
  methods:{
    // 获取商品分类列表数据
    async getCateList(){
      const { data: res } = await this.$http.get("categories");
      if(res.meta.status !== 200)  return this.$message.error("获取商品分类列表失败");
      this.catelist = res.data;
      // console.log(this.catelist);
    },
    // 级联选择器改变事件
    async cateChange(){
      this.getParamsList();
  
    },
    // 监听 页签点击 事件
    handleClick(){
      this.getParamsList();
    },
    // 获取参数列表 方法
    async getParamsList(){
      if(this.cateOption.length !== 3){
        this.cateOption = [];
        this.$message.warning("只允许选择三级菜单");
        return
      }
      // 请求参数 数据
      const { data: res } = await this.$http.get(`categories/${ this.cateId }/attributes`,
        { params:{ sel:this.activeName }});
      if(res.meta.status !== 200)  return this.$message.error("获取参数列表失败");
      // 得到属性可选参数数组
      res.data.forEach( item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : [];
        // 控制输入框展示
        item.inputVisible = false;
        //输入框的双向绑定
        item.inputValue = ''
      });
      console.log(res.data);
      if( this.activeName === 'many'){
        this.manyTableDate = res.data;
      }else{
        this.onlyTableDate = res.data;
      }
    },
    // 监听添加 属性/参数 对话框 关闭事件
    addInfoClose(){
      this.$refs.addInfoRef.resetFields();
    },
    // 添加 属性/参数 方法
    addParams(){
       // 表单提交的预校验
      this.$refs.addInfoRef.validate(async valid => {
        if(!valid) return this.$message.error("提交失败");
        // 发起网络请求，添加新用户
        const { data: res } = await this.$http.post(`categories/${ this.cateId}/attributes`,
            {
              attr_name:this.addInfoForm.attr_name,
              attr_sel:this.activeName
            });
        if(res.meta.status !== 201){
          this.$message.error("提交失败");
        }else{
          this.$message.success("添加成功");
          this.getParamsList();
          this.addDialogVisible = false;
        }     
      });
    },
    // 展示 编辑 属性 对话框
    async showEditDialog(id){
      const { data: res } = await this.$http.get(`categories/${ this.cateId }/attributes/${ id }`,
      { params:{ attr_sel:this.activeName }});
      if(res.meta.status !== 200)  return this.$message.error("获取参数列表失败");
      this.editInfoForm = res.data;
      this.editDialogVisible = true;
    },
    // 编辑 属性/参数 方法
    editParams(){
        // 表单提交的预校验
      this.$refs.editInfoRef.validate(async valid => {
        if(!valid) return this.$message.error("提交失败");
        // 发起网络请求，添加新用户
        const { data: res } = await this.$http.put(`categories/${ this.cateId }/attributes/${ this.editInfoForm.attr_id}`,
            {
              attr_name:this.editInfoForm.attr_name,
              attr_sel:this.activeName
            });
        if(res.meta.status !== 200){
          this.$message.error("修改失败");
        }else{
          this.$message.success("修改成功");
          this.getParamsList();
          this.editDialogVisible = false;
        }     
      });
    },
    // 展示 删除 属性 对话框
    async deleteDialog(id){
      // 提示用户是否确认删除
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        }).catch(err => err);
        // 如果用户确认删除,返回字符串confirm
        // 如果用户取消删除,返回字符串cancel
        // 判断用户是否真的删除
        if(confirmResult !== 'confirm'){
          return this.$message.info("已取消删除");
        }
        const {data: res} = await this.$http.delete(`categories/${ this.cateId }/attributes/${ id }`);
        if(res.meta.status !== 200){
          return this.$message.error(res.meta.msg);
        }
        this.$message.success("成功删除");
        this.getParamsList();
    },
    // 失去焦点或按下enter键触发事件
    async handleInputConfirm(row){
      // 先判断用户输入的是否合法
      if(row.inputValue.trim().length === 0){
        row.inputValue = '';
        row.inputVisible = false;
        return
      }else{
        // 输入合法，将输入框的值push到数组中
        row.attr_vals.push(row.inputValue);
        // 发起网络请求，将数据存储到数据库
        this.saveAttrValues(row);
      }
    },
    // 展示文本框
    showInput(row){
      row.inputVisible = true;
      // 文本框自动获得焦点
      // 页面加载完成后执行$nextTick 回调函数
      this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },
    // 保存tag标签数组数据 方法
    async saveAttrValues(row){
      const { data: res } = await this.$http.put(`categories/${ this.cateId }/attributes/${ row.attr_id }`,
        {
          attr_name:row.attr_name,
          attr_sel:row.attr_sel,
          attr_vals:row.attr_vals.join(' ')
        });
        if(res.meta.status !== 200)  return this.$message.error("修改参数项失败");
        this.$message.success("修改参数项成功");
        row.inputValue = '';
        row.inputVisible = false;
    },
    //  监听 tag 标签关闭事件的 方法
    handleClose(i,row){
      row.attr_vals.splice(i, 1);
      this.saveAttrValues(row);
    }
  },
  computed:{
    // 通过选中数组长度是否为3，决定是否禁用 添加参数 按钮
    isBtnDisable(){
      if(this.cateOption.length === 3){
        return false;
      }
      return true;
    },
    // 获取当前选中商品分类id
    cateId(){
      if(this.cateOption.length === 3){
        return this.cateOption[2];
      }
      return null;
    },
    // 计算对话框标题
    titleText(){
      if(this.activeName = 'many'){
        return '参数名称';
      }else{
        return '属性名称'
      }
    
    }
  }
}
</script>

<style lang="less" scoped>
  .row_style{
    margin: 15px 0;
  }
  .el-tag{
    margin: 10px;
  }
  .input-new-tag{
    width: 120px;
  }
</style>